<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="addressForm"
      :rules="rules"
      label-width="100px"
      class="address-form"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model.number="addressForm.userId" placeholder="请输入用户ID" />
      </el-form-item>
      
      <el-form-item label="联系人" prop="contact">
        <el-input v-model="addressForm.contact" placeholder="请输入联系人姓名" />
      </el-form-item>
      
      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="addressForm.mobile" placeholder="请输入手机号码" />
      </el-form-item>
      
      <el-form-item label="所在地区" required>
        <el-cascader
          v-model="selectedRegion"
          :options="regionOptions"
          :props="{
            value: 'value',
            label: 'label',
            children: 'children'
          }"
          placeholder="请选择所在地区"
          @change="handleRegionChange"
        />
      </el-form-item>
      
      <el-form-item label="详细地址" prop="street">
        <el-input 
          v-model="addressForm.street" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入详细地址，如街道、门牌号等" 
        />
      </el-form-item>
      
      <el-form-item label="是否默认" prop="isDefault">
        <el-switch v-model="addressForm.isDefault" :active-value="1" :inactive-value="0" />
      </el-form-item>
      
      <el-form-item label="备注" prop="notes">
        <el-input 
          v-model="addressForm.notes" 
          type="textarea" 
          :rows="2" 
          placeholder="请输入备注信息（选填）" 
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { AddressDTO } from '@/api/address'
import { createAddress, updateAddress } from '@/api/address'
import { getFullAreaData } from '@/utils/areaData'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '新增地址'
  },
  addressData: {
    type: Object as () => Partial<AddressDTO>,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'success'])

const dialogVisible = ref(props.visible)
const formRef = ref<FormInstance>()
const selectedRegion = ref<string[]>([])

// 表单数据
const addressForm = reactive<AddressDTO>({
  id: undefined as number | undefined,
  userId: undefined as number | undefined,
  contact: '',
  mobile: '',
  province: '',
  city: '',
  town: '',
  street: '',
  isDefault: 0,
  notes: ''
})

// 地区数据
interface RegionOption {
  value: string
  label: string
  children?: RegionOption[]
}

const regionOptions = ref<RegionOption[]>([])

// 初始化地区数据
const initRegionData = () => {
  regionOptions.value = getFullAreaData()
}

// 处理地区选择变化
const handleRegionChange = (value: string[]) => {
  if (value && value.length === 3) {
    addressForm.province = value[0]
    addressForm.city = value[1]
    addressForm.town = value[2]
  }
}

// 表单验证规则
const rules = reactive<FormRules>({
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number', message: '用户ID必须为数字', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  street: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
})

// 监听visible变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val
})

// 监听dialogVisible变化
watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val)
})

// 监听addressData变化
watch(() => props.addressData, (val) => {
  if (val && Object.keys(val).length > 0) {
    // 转换userId为数字类型
    const formData = { ...val }
    if (formData.userId) {
      formData.userId = Number(formData.userId)
    }
    if (formData.id) {
      formData.id = Number(formData.id)
    }
    Object.assign(addressForm, formData)
    // 设置级联选择器的值
    if (val.province && val.city && val.town) {
      selectedRegion.value = [val.province, val.city, val.town]
    }
  } else {
    resetForm()
  }
}, { deep: true })

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 转换userId为数字类型
        const formData = { ...addressForm }
        if (formData.userId) {
          formData.userId = Number(formData.userId)
        }
        if (formData.id) {
          formData.id = Number(formData.id)
        }

        if (formData.id) {
          // 更新地址
          await updateAddress(formData.id, formData)
          ElMessage.success('地址更新成功')
        } else {
          // 新增地址
          await createAddress(formData)
          ElMessage.success('地址添加成功')
        }
        emit('success')
        handleClose()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(addressForm.id ? '地址更新失败' : '地址添加失败')
      }
    } else {
      ElMessage.warning('请填写完整的地址信息')
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  Object.assign(addressForm, {
    id: undefined as number | undefined,
    userId: undefined as number | undefined,
    contact: '',
    mobile: '',
    province: '',
    city: '',
    town: '',
    street: '',
    isDefault: 0,
    notes: ''
  })
  selectedRegion.value = []
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

onMounted(() => {
  initRegionData()
})
</script>

<style scoped>
.address-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  padding: 4px 12px;
}

:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
}

:deep(.el-form-item__label) {
  line-height: 32px;
}

:deep(.el-switch) {
  margin: 4px 0;
}

:deep(.el-form-item__content) {
  flex: 1;
  display: flex;
  align-items: center;
}

:deep(.el-cascader) {
  width: auto;
  flex: 1;
}

:deep(.el-cascader .el-input) {
  width: 100%;
}

:deep(.el-cascader .el-input__wrapper) {
  width: 100%;
}
</style> 